package com.lhgray.sglhome.common

import android.content.Context
import android.content.pm.PackageManager
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ActivityContext
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

/**
 * 作者：lhgray on 2025/3/31.
 * 邮箱：lhgray@163.com
 * 文件：com.lhgray.sglhome.domain
 */
@Singleton
class PermissionHandlerImpl @Inject constructor(
    @ActivityContext private val context: Context
) {

    private val activity = context as? ComponentActivity
        ?: throw IllegalStateException("Must be called from an Activity context")

    fun checkPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(context, permission) ==
                PackageManager.PERMISSION_GRANTED
    }

    suspend fun requestPermission(permission: String): Boolean {
        return activity.requestPermission(permission)
    }

    private suspend fun ComponentActivity.requestPermission(permission: String): Boolean {

        return suspendCoroutine { continuation ->
            val launcher = registerForActivityResult(
                ActivityResultContracts.RequestPermission()
            ) { isGranted ->
                continuation.resume(isGranted)
            }
            launcher.launch(permission)
        }
    }
}